package com.qf.fengmimall.webSocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author 刘欣
 * @createTime 2023/2/20 14:58
 * @description
 */
@Component
@ServerEndpoint("/webSocket/{oid}")
@Slf4j
public class WebSocketServer {

    //多线程中，不用配置同步 用于保存页面 websocket连接对象的 map对象
    private static ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap<>();

    //打开webSocket连接
    @OnOpen
    public void onOpen(Session session, @PathParam("oid") String oid) throws IOException {
        session.getBasicRemote().sendText("from server" + oid);
        sessionMap.put(oid, session);

    }

    //响应客户端信息
    @OnMessage
    public void onMsg(Session session, String msg) throws IOException {
        session.getBasicRemote().sendText("from server" + msg);
    }

    /**
     * 提供外部调用
     *
     * @param oid
     * @param msg
     * @throws IOException
     */
    public static void sendMsg(String oid, String msg) throws IOException {
        Session session = sessionMap.get(oid);

        session.getBasicRemote().sendText(msg);

    }

    //管理连接处理
    @OnClose
    public void close(Session session, @PathParam("oid") String orderId) {

        sessionMap.remove(orderId);
    }

    //处理webSocket异常
    @OnError
    public void error(Throwable throwable) {

        log.debug("客户端连接出现问题");

    }
}
